import { PassportStrategy } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ExtractJwt, Strategy } from 'passport-jwt';
import type { StrategyOptions } from 'passport-jwt';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { adminAccount } from 'src/entities/adminAccount.entity';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  // 这里的 Strategy 必须是 passport-jwt 包中的
  constructor(
    config: ConfigService,
    @InjectRepository(adminAccount) private readonly userRepository: Repository<adminAccount>,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: 'suibianshenme'
    } as StrategyOptions);
  }

  async validate(payload: any) {
    console.log('qqqqqqqqqqq')
    const existUser = await this.userRepository.findOne({
      where: { id: payload.id },
    });
    if (!existUser) {
      console.log('ewqewqewqewqewqeqw')
      throw new UnauthorizedException('token验证失败')
    };

    return existUser;
  }
}
